function Missile(image, x, y, speed, angle, player) {
  this.image = image;
  this.x = x;
  this.y = y;
  this.vY = 0;
  this.speed = speed;
  this.angle = angle;
  this.player = player;

  this.life = 0;
  this.lifetime = 3;
  this.arm_time = 0.25 + Math.random() * 0.1 - 0.05;
  this.max_speed = 3000;
  this.target = null;

  this.trail = new Trail();
}

Missile.prototype.homeIn = function() { 
  var target_angle = Math.PI/2 - Math.atan2(this.target.x - this.x, this.target.y - this.y);
  var delta = (target_angle - this.angle) ;
  if (Math.abs(delta) < 5 * Math.PI/180) {
    this.angle += delta;
  }
  else { 
    this.angle += delta/Math.abs(delta) * 5.0 * Math.PI/180;
  }
  this.angle = this.angle % (2 * Math.PI);
}

Missile.prototype.getDistance = function(x, y) {
  var dx = x - this.x;
  var dy = y - this.y; 
  return Math.sqrt(dx * dx + dy * dy);
}

Missile.prototype.getTarget = function(planes) { 
  var distance = null;
  var min_distance = 700;
  var min_idx = -1;
  for (var i = 0; i < planes.length; i++) {
    distance = this.getDistance(planes[i].x, planes[i].y);
    if (planes[i] != this.player && distance < min_distance) {
      min_distance = distance;
      min_idx = i;
    }
  }
  if (min_idx > -1) {
    this.target = planes[min_idx];
  }
}


Missile.prototype.update = function(dt, planes) { 
  this.life += dt;
  if (this.life > this.lifetime) {
    return 0;
  }
  
  if (this.life > this.arm_time) {
    if (this.target == null) {
      this.getTarget(planes);
    }
    else {
      this.homeIn();
    }
    this.trail.update(this.x, this.y, dt);
  }
  else {
    this.vY += 300 * dt;
    this.y += this.vY * dt;
    this.speed -= 100 * dt;
  }
  this.x += this.speed * Math.cos(this.angle) * dt;
  this.y += this.speed * Math.sin(this.angle) * dt;
  if (this.life > this.arm_time && this.speed < this.max_speed) { 
    this.speed += 4000 * dt;
  }
  return 1;
}

Missile.prototype.render = function(context) {
  context.save();
  context.translate(this.x, this.y);
  context.rotate(this.angle);

  context.beginPath();
  context.moveTo(0, 0);  
  context.strokeStyle = 'rgb(255, 100, 100)';
  context.lineWidth = 6;
  context.lineCap = 'square';
  context.lineTo(20, 0);
  context.stroke();
  //context.drawImage(this.image, 0, 0);
  context.restore();

  if (this.life > this.arm_time) {
    this.trail.render(context);
  }  
}
